(function() {
  var Async, Commodity, Fs, autoAddTag, getAllItems, viewDataHandler, _;

  Async = require('async');

  Commodity = require('./commodity');

  _ = require('underscore');

  Fs = require('fs');

  viewDataHandler = {
    /**
     * [home description]
     * @param  {[type]} cbf [description]
     * @return {[type]}     [description]
    */

    home: function(query, options, cbf) {
      query = query || {};
      return Async.parallel({
        total: function(cbf) {
          return Commodity.count(query, cbf);
        },
        data: function(cbf) {
          return Commodity.find(query, options, cbf);
        }
      }, function(err, results) {
        return cbf(err, results);
      });
    },
    commodity: function(id, cbf) {
      return Commodity.find({
        _id: id
      }, cbf);
    },
    commodityModify: function(id, data, cbf) {
      return Commodity.findByIdAndUpdate(id, data, cbf);
    },
    table: function(cbf) {
      return Commodity.find({}, cbf);
    }
  };

  autoAddTag = function(key, tag) {
    return Commodity.find({}, null, function(err, data) {
      var docs;
      docs = [];
      return _.each(data, function(item) {
        var id;
        if (item.title.indexOf(key) !== -1) {
          item = item.toObject();
          if (_.indexOf(item.tags, tag) === -1) {
            item.tags.push(tag);
            item.modifiedTime = new Date();
            id = item._id;
            delete item._id;
            delete item.__v;
            if (!item.pics) {
              delete item.pics;
            }
            return Commodity.findByIdAndUpdate(id, item, function(err) {
              console.log(item);
              return console.log(err);
            });
          }
        }
      });
    });
  };

  autoAddTag('太古', '太古');

  getAllItems = function() {
    return Commodity.find({}, null, function(err, data) {
      var docs, saveData;
      docs = [];
      _.each(data, function(item) {
        item = item.toObject();
        delete item._id;
        delete item.__v;
        return docs.push(item);
      });
      saveData = JSON.stringify(docs);
      return Fs.writeFile('/Users/vicanso/workspace/tmp/data.json', saveData, function(err) {
        return console.log("err:" + err);
      });
    });
  };

  module.exports = viewDataHandler;

}).call(this);
